# 服务器访问权限配置脚本
param(
    [string]$ServerIP = "10.3.255.92",
    [string]$Username = "",
    [string]$LocalUser = $env:USERNAME
)

Write-Host "=== 服务器访问权限配置 ===" -ForegroundColor Green
Write-Host "服务器IP: $ServerIP" -ForegroundColor Cyan
Write-Host "本地用户: $LocalUser" -ForegroundColor Cyan

# 检查PowerShell远程配置
function Test-PsRemoting {
    param([string]$ServerIP)
    try {
        $result = Test-WSMan -ComputerName $ServerIP -ErrorAction Stop
        Write-Host "PowerShell远程服务已启用: $ServerIP" -ForegroundColor Green
        return $true
    } catch {
        Write-Host "PowerShell远程服务未启用或无法连接: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 生成配置指南
function Show-SetupGuide {
    Write-Host "`n=== 服务器配置指南 ===" -ForegroundColor Yellow
    Write-Host "请在服务器（$ServerIP）上执行以下操作：" -ForegroundColor Cyan
    
    Write-Host "`n1. 启用PowerShell远程访问（以管理员身份运行）：" -ForegroundColor Green
    Write-Host "   Enable-PSRemoting -Force" -ForegroundColor White
    
    Write-Host "`n2. 设置防火墙规则：" -ForegroundColor Green
    Write-Host "   Enable-NetFirewallRule -DisplayGroup 'Windows Remote Management'" -ForegroundColor White
    
    Write-Host "`n3. 配置CredSSP（如果需要）：" -ForegroundColor Green
    Write-Host "   Enable-WSManCredSSP -Role Server" -ForegroundColor White
    
    Write-Host "`n4. 设置文件共享权限：" -ForegroundColor Green
    Write-Host "   # 在服务器上设置D:\Service共享" -ForegroundColor White
    Write-Host "   New-SmbShare -Name 'Service' -Path 'D:\Service' -FullAccess '$LocalUser'" -ForegroundColor White
    
    Write-Host "`n5. 测试连接：" -ForegroundColor Green
    Write-Host "   Test-WSMan -ComputerName $ServerIP" -ForegroundColor White
}

# 创建快捷部署脚本
function Create-DeployScript {
    $deployScript = @"
# 一键部署脚本 - 保存密码版本
param(`
    [string]`$ServerIP = "10.3.255.92",
    [string]`$Username = "$Username",
    [string]`$Password = ""  # 这里填写密码
)

if ([string]::IsNullOrEmpty(`$Password)) {
    `$Password = Read-Host "请输入服务器密码" -AsSecureString | ConvertFrom-SecureString -AsPlainText
}

.\remote-deploy.ps1 -Deploy -ServerIP `$ServerIP -Username `$Username -Password `$Password
"@
    
    $deployScriptPath = Join-Path $PSScriptRoot "deploy-quick.ps1"
    $deployScript | Out-File -FilePath $deployScriptPath -Encoding UTF8
    Write-Host "已创建快捷部署脚本: $deployScriptPath" -ForegroundColor Green
}

# 主逻辑
if (-not (Test-PsRemoting -ServerIP $ServerIP)) {
    Show-SetupGuide
    Create-DeployScript
} else {
    Write-Host "服务器已配置好远程访问权限" -ForegroundColor Green
    Create-DeployScript
}

Write-Host "`n=== 使用说明 ===" -ForegroundColor Yellow
Write-Host "1. 先在服务器上配置PowerShell远程访问" -ForegroundColor Cyan
Write-Host "2. 然后使用: .\deploy\remote-deploy.ps1 -Deploy -Username '用户名' -Password '密码'" -ForegroundColor Cyan
Write-Host "3. 或使用快捷脚本: .\deploy\deploy-quick.ps1" -ForegroundColor Cyan